package main

import (
	"bytes"
	"encoding/binary"
	"fmt"
	"log"
	"net"
	"os"
	"strings"
)

type Request struct {
	frame_type uint64
	buf_size   uint64
}

var EOS_TAG = "<EOS>"

func main() {
	//
	chunk := int(16000 * 0.4)
	dec_size := 0
	port := "8000"
	ip := "127.0.0.1"
	data, _ := Synthesis_test()
	//check := 0
	//tmp_result := ""
	out := ""
	result := ""
	addr := ip + ":" + port            //定义主机名
	conn, err := net.Dial("tcp", addr) //拨号操作，需要指定协议。
	defer conn.Close()
	if err != nil {
		fmt.Println(err.Error())
	}
	var typ int
	fmt.Println("进入循环发送", chunk)
	for ; dec_size+chunk < len(data); dec_size = dec_size + chunk {
		fmt.Println(dec_size+chunk, len(data))
		if dec_size == 0 {
			typ = 0
		} else {
			typ = 1
		}
		temp := data[0+dec_size : 0+dec_size+chunk]
		fmt.Println("进入request")
		out, err = request(temp, typ, conn)
		fmt.Println("出request")
		fmt.Println(out)
		if err != nil {
			fmt.Println(err.Error())
		}
	}
	result = out
	fmt.Println("最后前结果" + result)
	fmt.Println("进入最后发送")
	chunk = len(data) - dec_size
	if chunk > 0 {
		typ = 2
		temp := data[0+dec_size : 0+dec_size+chunk]
		out, err = request(temp, typ, conn)
	}
	if out != "" {
		result = out
	}
	fmt.Println("总发送结束", "结果为："+result)
	fmt.Println(result)
}

func request(in []byte, typ int, conn net.Conn) (out string, err error) {
	buf, err := Object2Bytes(len(in), typ)
	n, err := conn.Write(buf)
	fmt.Println("一次发送结束")
	n, err = conn.Write(in)
	fmt.Println("二次发送结束")
	for true {
		buf := make([]byte, 1024)
		n, err = conn.Read(buf)
		str := byte2str(buf[:n])
		fmt.Println("res::" + str)
		fmt.Println(strings.Contains(str, EOS_TAG))
		if strings.Contains(str, EOS_TAG) {
			ind := strings.Index(str, EOS_TAG)
			out = out + str[:ind]
			break
		} else {
			out = out + str
		}
		fmt.Println(out)
	}
	return
}

//本地测试合成
func Synthesis_test() (data []byte, err error) {
	fileName := "tts1.wav"
	file, err := os.Open(fileName)
	defer file.Close()
	stats, err := file.Stat()
	data = make([]byte, stats.Size())
	count, err := file.Read(data)
	fmt.Printf("read file %s len: %d \n", fileName, count)
	return
}

//对象生成序列
func Object2Bytes(buf_size int, frame_type int) (data []byte, err error) {
	var req Request
	req.buf_size = uint64(buf_size)
	req.frame_type = uint64(frame_type)
	buf := &bytes.Buffer{}
	if err := binary.Write(buf, binary.LittleEndian, req); err != nil {
		log.Fatal("binary write error:", err)
	}
	data = buf.Bytes()
	for i := 4; i < 8; i++ {
		data[i] = byte(47)
	}
	return
}

//
func byte2str(data []byte) (str string) {
	str = string(data)
	return
}
